package com.ding.dailyup.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.date.DateUtil;
import com.ding.dailyup.config.SystemConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ding.dailyup.annotation.LoginUser;
import com.ding.dailyup.constant.StockConstant;
import com.ding.dailyup.emum.StrategyStatusEnum;
import com.ding.dailyup.entity.JsonResult;
import com.ding.dailyup.entity.response.StockRecommendResp;
import com.ding.dailyup.entity.response.ZhishuResp;
import com.ding.dailyup.enums.StockImgLevelEnum;
import com.ding.dailyup.exception.BOException;
import com.ding.dailyup.model.StockRecommend;
import com.ding.dailyup.model.StockStrategy;
import com.ding.dailyup.model.UserBuyStrategy;
import com.ding.dailyup.model.UserCollectStock;
import com.ding.dailyup.service.StockRecommendService;
import com.ding.dailyup.service.StockStrategyService;
import com.ding.dailyup.service.UserService;
import com.ding.dailyup.util.StockUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/daily/stock")
@Api(tags = "每日股票")
public class StockController {
	private static Logger logger = LoggerFactory
			.getLogger(StockController.class);
	@Autowired
	private StockRecommendService stockRecommendService;
	@Autowired
	private UserService userService;
	@Autowired
	private StockStrategyService stockStrategyService;

	@GetMapping("/list")
	@ApiOperation(value = "每日股票查询")
	public JsonResult<List<StockRecommendResp>> getDailyStock(
			@ApiParam(value = "策略id") @RequestParam(value = "strategyId") Long strategyId,
			@ApiParam(value = "日期, 精确到时分秒, 转毫秒时间戳 ") @RequestParam(value = "dateTimestamp") long dateTimestamp,
			@LoginUser Long userId) {

		// 判断策略是否可用
		StockStrategy strategy = stockStrategyService.findById(strategyId);

		// 如果策略是收费的,
		if (!StrategyStatusEnum.usable(strategy.getStatus())) {
			// 查看是否购买过
			boolean buy = userService.getUserBuyStrategy(userId).stream()
					.map(UserBuyStrategy::getStrategyId)
					.anyMatch(i -> i.equals(strategyId));
			if (!buy) {
				throw new BOException("您好, 请先联系客服获取该策略");
			}
		}

		// 按照策略查询股票
		List<StockRecommend> recommend = stockRecommendService
				.findRecommend(strategyId, dateTimestamp);
		List<String> userCollectStocks = Lists.newArrayList();

		// 设置用户收藏状态
		if (userId != 0) {
			userCollectStocks = userService.listUserCollectStocks(userId)
					.stream().map(UserCollectStock::getStockCode)
					.collect(Collectors.toList());
		}
		List<String> finalUserCollectStocks = userCollectStocks;
		List<StockRecommendResp> rs = recommend.stream().map(item -> {
			StockRecommendResp resp = new StockRecommendResp();
			BeanUtil.copyProperties(item, resp);
			String raiseDownImgUrl = StockUtil.getRaiseDownImgUrl(
					item.getStockCode(), StockImgLevelEnum.DAILY.level(),
					System.currentTimeMillis());
			resp.setDailyRaiseAndFallImgUrl(raiseDownImgUrl);
			resp.setCollected(
					finalUserCollectStocks.contains(item.getStockCode()));
			resp.setStockCode(item.getStockCode());
			return resp;
		}).collect(Collectors.toList());
		return JsonResult.succResult(rs);
	}

	// 每日股票上传
	@PostMapping(value = "/upload")
	@ApiOperation(value = "每日股票上传")
	public JsonResult uploadDailyStock(
			@ApiParam(value = "上传每日推荐股票") @RequestBody JSONObject stockUpload,
			HttpServletRequest request) {
		String adminToken = request.getHeader("adminToken");

		// 验证权限
		if ("dingguanghui888".equals(adminToken)) {
			DateTimeFormatter df = DateTimeFormatter
					.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime date = StrUtil
					.isNotBlank(stockUpload.getString("uploadDate"))
							? LocalDateTime.parse(
									stockUpload.getString("uploadDate"), df)
							: LocalDateTime.now();
			JSONArray dataArray = stockUpload.getJSONArray("data");
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject jsonObject = dataArray.getJSONObject(i);
				Long strategyId = jsonObject.getLong("strategyId");
				List<String> stockCodes = JSONObject.parseArray(
						jsonObject.getJSONArray("stockCodes").toJSONString(),
						String.class);
				logger.info("开始上传个股,策略id:{},个股信息:{}", strategyId,
						Joiner.on(",").join(stockCodes));
				stockRecommendService.uploadStock(strategyId, date, stockCodes);
			}
		} else {
			throw new BOException("管理员接口权限检查异常");
		}
		return JsonResult.succResult();
	}

	@GetMapping("/zhishu")
	@ApiOperation(value = "获取指数")
	public JsonResult<List<ZhishuResp>> listZhishu() {
		List<String> codesWithHouse = Lists.newArrayList(StockConstant.SHANGHAI,
				StockConstant.SHENZHENG, StockConstant.CHUANGYE);
		String resp = HttpUtil.get(StockConstant.QT_STOCK_URL
				+ Joiner.on(",").join(codesWithHouse));
		String[] raws = resp.split("\n");
		List<ZhishuResp> zhishu = Lists.newArrayList();

		if (codesWithHouse.size() != raws.length) {
			return JsonResult.succResult(zhishu);
		}
		for (int i = 0; i < codesWithHouse.size(); i++) {
			String symbol = codesWithHouse.get(i);
			String raw = raws[i];
			String assertion = String.format("(?<=v_%s=\").*?(?=\";)", symbol);
			Pattern pattern = Pattern.compile(assertion);
			Matcher matcher = pattern.matcher(raw);
			while (matcher.find()) {
				String[] metas = matcher.group().split("~");
				zhishu.add(new ZhishuResp(metas[1], metas[2], metas[3],
						metas[32]));
			}
		}
		return JsonResult.succResult(zhishu);
	}
}
